<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------

namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo  活动模型
 * @since 2015-7-13
 */

class ActivityModel extends BaseModel {

    /* 自动验证规则 */
    protected $_validate = array(
        array('activity_name', 'require', '活动名称必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('activity_category_id', 'integer', '活动分类必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('activity_name', '1,80', '活动名称不能超过3个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('sms_content', 'require', '短信 内容必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('sms_content', '1,80', '短信内容不能超过80个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('start_time', 'require', '开始日期必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('end_time', 'require', '结束日期必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('show_start_time', 'require', '系统上线日期必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('show_end_time', 'require', '系统下线日期必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('is_online', '0,1', '线上线下状态有误', self::EXISTS_VALIDATE, 'in', self::MODEL_BOTH),
    	/* array('expect_money', 'double', '预计收入必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('expect_member_num', 'double', '预计报名人数必须填写', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH), */
    		
    );
  
    /* 自动完成规则 */
    protected $_auto = array(
        array('status', 1, self::MODEL_INSERT, 'string'),
    	array('create_user_id', 'getUid', self::MODEL_INSERT, 'callback'),
    	array('start_time', 'getTime', self::MODEL_BOTH, 'callback'),
    	array('end_time', 'getTime', self::MODEL_BOTH, 'callback'),
    	array('show_start_time', 'getTime', self::MODEL_BOTH, 'callback'),
    	array('show_end_time', 'getTime', self::MODEL_BOTH, 'callback'),
        array('update_time', 'time', self::MODEL_BOTH, 'function'),
    	array('create_time', 'time', self::MODEL_INSERT, 'function'),
    );

    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function getPk(){
    	return 'activity_id';
    }
    
    /**
     * @todo 返回创建人
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    static protected function getUid(){
    	return UID;
    } 
    
    /**
     * @todo 返回默认插入状态
     * @return number
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    static protected function getTime($time){
    	return strtotime($time);
    }
    
    /**
     * @todo 检测活动是否存在
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public  function activityIs($map){
    	if(!array_key_exists('status', $map)){
    		$map['status']=1;
    	}
    	$info = $this->where($map)->find();
    	if(!empty($info)){
    		return $info;
    	}
    	$this->error='活动不存在活已被禁用';
    	return false;
    }
    
    /**
     * @todo 检测活动详细内容是否存在
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function activityDetailIs($map){
    	$info = M('ActivityDetail')->where($map)->find();
    	if(!empty($info)){
    		return $info;
    	}
    	return false;
    }
    
 
    
   
    
    /**
     * 新增或更新一个活动
     * @return boolean fasle 失败 ， int  成功 返回完整的数据
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function update(){
        /* 获取数据对象 */
        $data = $this->create($_POST);
        if(empty($data)){
            return false;
        }
        //时间段的验证
        if($data['start_time'] >= $data['end_time']){
        	$this->error ='结束日期不能小于开始日期';
        	return false;
        }
        if($data['show_start_time'] >= $data['show_end_time']){
        	$this->error ='下线时间不能小于上线时间';
        	return false;
        }
        $expect_money= (int)trim(I('post.expect_money'));
        if($expect_money =='' ){
        	$this->error = '预计收入不能为空,并且需要为货币！';
        	return false;
        }
        $detail_data['expect_money'] = $expect_money;
        $expect_member_num = (int)I('post.expect_member_num');
        $detail_data['expect_member_num'] = $expect_member_num;
        
        if(empty($data[$this->getPk()])){ //新增数据
        	$this->startTrans();
            $id = $this->add($data); 
            if(!$id){
            	$this->rollback();
                $this->error = '新增活动出错！';
                return false;
            }
            $detail_data[$this->getPk()]=$id;
            if(!M('ActivityDetail')->add($detail_data)){
            	$this->rollback();
            	$this->error = '新增活动附属信息出错！';
            	return false;
            }
            $this->commit();
            $activity_theme_id = (int)I('activity_theme_id');
            
            // 选择继承的模版插入对应的数据
            if($activity_theme_id!=0){
            	 $this->createHistoryTheme($id, $activity_theme_id);
            }
            
            /*
             选择默认模版下
             if $_POST['is_template'] == 1
             $template_data = 获取默认活动模版填写的字段集（活动时间、活动地点、活动简介、活动规则等）
             M('activity_template')->add($template_data);
             */
            
            //创建活动
            $this->activityLogInsert($id,1);
        } else {
        	$id = (int)$data[$this->getPk()];
        	if($id ==0){
        		$this->error = '请不要非法攻击.~！';
        		return false;
        	}
        	$map = array('status'=>1,$this->getPk()=>$id);
        	if(false === $this->activityIs($map)){
        		return false;
        	}
        	unset($data['is_online']);//活动上线下线属性不允许随意更改
        	$this->startTrans();
            $status = $this->where($map)->save($data); //更新基础内容
            if(false === $status){
            	$this->rollback();
                $this->error = '更新活动出错！';
                return false;
            }
            if(false === $this->activityDetailIs($map)){
            	$this->rollback();
            	$this->error = '该活动没有详细信息';
            	return false;
            }
            if(false === M('ActivityDetail')->where($map)->save($detail_data)){
            	$this->rollback();
            	$this->error = '更新活动附属信息出错！';
            	return false;
            }
            
            /*
             选择默认模版下
             if $_POST['is_template'] == 1
             $template_data = 获取默认活动模版填写的字段集（活动时间、活动地点、活动简介、活动规则等）
             [事务]   M('activity_template')->where(array('activity' => xxx))->save($template_data);
             */
            
            $this->commit();
            //更新活动
            $this->activityLogInsert($id,2);
        }
        return $data;
    }
    /**
	 * @todo   创建活动通过历史模板和模块的录入
	 * @param  int activity_id 活动id
	 * @param  int theme_id    模板id
	 * @author fang
	 */
    public function createHistoryTheme($activity_id,$theme_id){
    	$activity_id = (int)$activity_id;
    	if($activity_id ==0){
    		$this->error ='activity_id参数有误';
    		return false;
    	}
    	$theme_id = (int)$theme_id;
    	if($theme_id ==0){
    		$this->error ='theme_id参数有误';
    		return false;
    	}
        //活动判断
        $activity = M('activity')->field('activity_id')->where(array('activity_id' => $activity_id, 'status' => 1))->find();
        if(empty($activity)){
            $this->error ='活动不存在！';
            return false;
        }
        //模板判断（获取）
        $theme_field = 'theme_name,content_head,content,content_foot,start_time,end_time,type';
        $theme = M('activity_theme')->field($theme_field)->where(array('activity_theme_id' => $theme_id, 'status' => 1))->find();
        if(empty($activity)){
            $this->error = '模板不存在！';
            return false;
        }
        //活动模板关系判断/获取
        $activity_theme = M('activity_theme_relation')->where(array('activity_id' => $activity_id, 'theme_id' => $theme_id))->find();
        if($activity_theme){
            $this->error = '当前活动已创建过当前模板！';
            return false;
        }
        //模板模块关系判断/获取
        $module = M('activity_theme_module')->field('module_id,position')->where(array('theme_id' => $theme_id))->select();
        if(empty($module)){
            $this->error = '模块不存在！';
            return false;
        }
        //模块获取
        $positon = array_column($module, 'position', 'module_id');
        $module_field = 'activity_module_id,module_name,module_content,start_time,end_time';
        $where_module['activity_module_id'] = array('in', array_column($module, 'module_id')); 
        $where_module['status'] = 1;
        $module_list = M('activity_module')->field($module_field)->where($where_module)->select();

        $start = 0;
        M()->startTrans();
        //模板添加
        $theme['create_time'] = NOW_TIME;
        $theme['update_time'] = NOW_TIME;
        $theme['create_user_id'] = UID;
        $add_theme = M('activity_theme')->add($theme);
        if(empty($add_theme)){
            $start++;
        }
        $data_activity = array(
            'activity_id' => $activity_id,
            'theme_id' => $add_theme
        );
        $add_activity_theme = M('activity_theme_relation')->add($data_activity);
        if(empty($add_activity_theme)){
            $start++;
        }
        //模块数据处理
        for($i=0; $i<count($module_list); $i++){
            //模块添加
            $data_module = array(
                'module_name' => $module_list[$i]['module_name'],
                'module_content' => $module_list[$i]['module_content'],
                'start_time' => $module_list[$i]['start_time'],
                'end_time' => $module_list[$i]['end_time'],
                'cteate_time' => NOW_TIME,
                'update_time' => NOW_TIME,
                'create_user_id' => UID
            );
            $add_module = M('activity_module')->add($data_module);
            usleep(100);//休息休息 马胜杰
            if(empty($add_module)){
                $start++;
            }
            //关系添加
            $data = array(
                'activity_id' => $activity_id,
                'theme_id' => $add_theme,
                'module_id' => $add_module,
                'position' => $positon[$module_list[$i]['activity_module_id']],
            );
            $add_theme_module = M('activity_theme_module')->add($data);
            usleep(100);//休息休息 马胜杰
            if(empty($add_theme_module)){
                $start++;
            }
        }
        if($start == 0){
            M()->commit();
        }else{
            M()->rollback();
            $this->error = '创建模板模块出错！';
            return false;
        }
        return true;
    }
    
    /**
	 * @todo   根据活动ID获取下属模板及模块
	 * @param  int activity_id 活动id
	 * @author fang
	 */
    public function getThemeModule($activity_id){
    	$table_pre = C('DB_PREFIX');
        //获取相应模板
        $field_theme = 'theme_id,theme_name,start_time,end_time';
        $join_theme = $table_pre.'activity_theme on '.$table_pre.'activity_theme.activity_theme_id = '.$table_pre.'activity_theme_relation.theme_id';
        $where_theme = array(
            'activity_id' => $activity_id,
            'status' => 1
        );
        $theme = M('activity_theme_relation')->field($field_theme)->join($join_theme)->where($where_theme)->select();
        if(empty($theme)){
            return array();
        }
        //获取相应模块
        $field_module = 'activity_id,theme_id,module_id,position,module_name,start_time,end_time';
        $join_module = $table_pre.'activity_module on '.$table_pre.'activity_module.activity_module_id = '.$table_pre.'activity_theme_module.module_id';
        $where_module = array(
            'activity_id' => $activity_id,
            'theme_id' => array('in', array_column($theme, 'theme_id')),
            'status' => 1
        );
        $module = M('activity_theme_module')->field($field_module)->join($join_module)->where($where_module)->select();
        //数组组合
        $array = array();
        for($j=0; $j<count($module); $j++){
            $array[$module[$j]['theme_id']]['data'][$module[$j]['position']]['position'] = $module[$j]['position'];
            $array[$module[$j]['theme_id']]['data'][$module[$j]['position']]['module_list'][] = array(
                'module_id' => $module[$j]['module_id'],
                'module_name' => $module[$j]['module_name'],
                'start_time' => $module[$j]['start_time'],
                'end_time' => $module[$j]['end_time'],
            );
        }
        for($i=0; $i<count($theme); $i++){
            $theme[$i]['data'] = array_merge($array[$theme[$i]['theme_id']]['data']);
        }
        return $theme;
    }
    
    /**
     * @todo    模板更新
     * @param   activity_theme_id   模板ID
     *          activity_id         活动ID
     *          status              状态（默认1）
     *          sort                排序（默认0）
     *          theme_name          模板名称
     *          content             模板内容
     * @result  $data   成功
     *          false   失败
     * @author  fang
     */
    public function themeUpdate(){
        
        $activity_theme_id = (int)I('post.activity_theme_id');
        $activity_id = (int)I('post.activity_id');
        
        $data['create_user_id'] = UID;
        $data['status'] = (int)I('post.status');
        $data['sort'] = (int)I('post.sort');
        $data['type'] = (int)I('post.type');
        $data['theme_name'] = trim(I('post.theme_name'));
        $data['content'] = I('post.content');
        $data['content_head'] = I('post.content_head');
        $data['content_foot'] = I('post.content_foot');
        $data['update_time'] = NOW_TIME;
        $data['start_time'] = strtotime(I('post.start_time'));
        $data['end_time'] = strtotime(I('post.end_time'));
        
        $data_relation['activity_id'] = $activity_id;
        
        if($data['theme_name'] == ''){
            $this->error = '请填写模块名称！';
            return false;
        }
        if(strlen($data['theme_name']) >= 30){
            $this->error = '模板名称不能超过30个字符！';
            return false;
        }
        if($data['start_time'] >= $data['end_time']){
        	$this->error ='结束日期要大于开始时间';
        	return false;
        }
        if($data['start_time'] >= $data['end_time']){
        	$this->error ='结束日期要大于开始时间';
        	return false;
        }
        if(empty($activity_id)){
        	//空模版
            /* $this->error = '请选择对应活动！';
            return false; */
        }else {
        	//活动隶属模版
        	if(false == $this->isThemeAdd($activity_id, $activity_theme_id ,$data)){
        		return false;
        	}
        }
        
        if(empty($activity_theme_id)){
            if(empty($data['content'])){
                $this->error = '请添加模板主体信息！';
                return false;
            }
        }
        if(empty($data['content_head']) || empty($data['content_foot'])){
            $this->error = '请添加模板信息！';
            return false;
        }
        
        
        M()->startTrans();
        /* 添加或新增行为 */
        if(empty($activity_theme_id)){ 
            //新增数据
            $data['create_time'] = NOW_TIME;
            $id = M('activity_theme')->add($data);
            //新增关联表
            $data_relation['theme_id'] = $id;
            $id_relation = M('activity_theme_relation')->add($data_relation);
            //模块处理
            $result_module = $this->moduleUpdate($data['content'],$activity_id,$id);
            //
            if($id > 0 && $id_relation > 0 && $result_module !== false){
                M()->commit();
            }else{
                M()->rollback();
                $this->error = '新增模板出错！';
                return false;
            }
            $data['message'] = '创建成功！';
            //记录行为
            action_log('theme_add', 'activity_theme', $id, UID);
        } else { 
            //更新主题表
            $where['activity_theme_id'] = $activity_theme_id;
            //模板主体内容禁止修改
            unset($data['content']);
            $result = M('activity_theme')->where($where)->save($data);
            //更新关联表
            $where_relation['theme_id'] = $activity_theme_id;
            $result_relation = M('activity_theme_relation')->where($where_relation)->save($data_relation);
            //模块处理（暂无）
            if($result !== false && $result_relation !== false){
                M()->commit();
            }else{
                M()->rollback();
                $this->error = '更新模板出错！';
                return false;
            }
            $data['message'] = '更新成功！';
            //记录行为
            action_log('theme_edit', 'activity_theme', $activity_theme_id, UID);
            //缓存更新
            $this->cacheChange($activity_id,0,2);
        }
        return $data;
    }
    
    /**
     * @todo    模块添加
     * @param   $content        模板内容
     *          $activity_id    活动ID
     *          $theme_id       模板ID
     * @author  fang
     */
    public function moduleUpdate($content,$activity_id,$theme_id){
    	$activity_id = (int)$activity_id;
    	/* if($activity_id==0){
    		$this->error ='活动参数有误';
    		return false;
    	} */
    	if($activity_id > 0){
    		if(!$this->activityIs(array('status'=>1,'activity_id'=>$activity_id))){
    			$this->error ='活动不存在或被禁用';
    			return false;
    		}
    	}
    	$theme_id = (int)$theme_id;
    	if($theme_id == 0){
    		$this->error ='主题参数有误';
    		return false;
    	}
    	
        //获取模块列表
        $out = $this->themeModuleRegular($content);
        if(false == $out){
            $this->error ='模板解析失败';
    		return false;
        }
        $data = array(
            'module_name' => '',
            'module_content' => '',
            'status' => 1,
            'sort' => 0,
            'create_user_id' => UID,
            'cteate_time' => NOW_TIME,
            'update_time' => NOW_TIME
        );
        $data_module = array(
            'activity_id' => $activity_id,
            'theme_id' => $theme_id
        );
        for($i = 0; $i < count($out[1]); $i++){
            //添加模块表
            $add = M('activity_module')->add($data);
            usleep(10);//休息休息  马胜杰
            if($add){
                $data_module = array(
                    'activity_id' => $activity_id,
                    'theme_id' => $theme_id,
                    'module_id' => $add,
                    'position' => (int)$out[1][$i],
                );
                //添加模块关系表
                $add_module = M('activity_theme_module')->add($data_module);
                if($add_module === false){
                    return false;
                }
            }else{
                return false;
            }
        }
        return true;
    }
    
    /**
     * @todo    单模块数据更新
     * @param   $_POST
     *          @添加
     *          $position       模块位置ID
     *          $theme_id       模板ID
     *          $activity_id    活动ID
     *          @更新
     *          $data           表信息字段
     * @author  fang
     */
    public function oneModuleUpdate(){

        $position = (int)I('post.position');
        $theme_id = (int)I('post.theme_id');
        $activity_id = (int)I('post.activity_id');
        $type = (int)I('post.type');
        $activity_module_id = (int)I('post.activity_module_id');
        
        $data['module_name'] = I('post.module_name');
        $data['module_content'] = str_replace("&#39;", "'", htmlspecialchars_decode(I('post.content')));//htmlspecialchars_decode
        $data['start_time'] = strtotime(I('post.start_time'));
        $data['end_time'] = strtotime(I('post.end_time'));
        $data['update_time'] = NOW_TIME;
        $data['create_user_id'] = UID;
        
        if(empty($data['module_name'])){
            $this->error = '请添加模块名称！';
            return false;
        }
        if(strlen($data['module_name']) >= 30){
            $this->error = '模块名称不能超过30个字符！';
            return false;
        }
        if($data['start_time'] >= $data['end_time']){
            $this->error ='结束日期要大于开始时间';
            return false;
        }
        if(false == $this->isModuleAdd($activity_id, $theme_id ,$position ,$activity_module_id ,$data)){
            return false;
        }
        if(empty($data['module_content'])){
            $this->error = '请添加模块内容！';
            return false;
        }
        if($activity_module_id == 0){
            if($position == 0){
                $this->error = '请选择模块展示位置！';
                return false;
            }
            $data['cteate_time'] = NOW_TIME;
            //添加操作
            M()->startTrans();
            //添加模块
            $add = M('activity_module')->add($data);
            $data_module['activity_id'] = $activity_id;
            $data_module['theme_id'] = $theme_id;
            $data_module['module_id'] = $add;
            $data_module['position'] = $position;
            //添加模块关系
            $add_module = M('activity_theme_module')->add($data_module);
            if($add > 0 && $add_module > 0){
                M()->commit();
            }else{
                M()->rollback();
            }
            action_log('module_add', 'activity_module', $add, UID);//记录行为
        }else{
            //更新操作
            $where['activity_module_id'] = $activity_module_id;
            if(!M('activity_module')->field('activity_module_id')->where($where)->find()){
                $this->error = "模块不存在！";
                return false;
            }
            //更新模块
            if(false === M('activity_module')->where($where)->save($data)){
                return false;
            }
            action_log('module_edit', 'activity_module', $activity_module_id, UID);//记录行为
        }
        //缓存更新
        $this->cacheChange($activity_id,0,2);
        return $data;
    }
    
    /**
     * @todo    是否可以添加模板（判断时间）
     * @param   $activity_id            活动ID
     *          $activity_theme_id      模板ID
     *          $data                   数组
     * @author  fang
     */
    public function isThemeAdd($activity_id, $activity_theme_id, $data){
        //活动时间判断
        $where_activity['activity_id'] = $activity_id;
        $where_activity['status'] = 1;
        $activity = M('activity')->field('show_start_time,show_end_time')->where($where_activity)->find();
        if((int)$activity['show_end_time'] < $data['start_time'] || (int)$activity['show_start_time'] > $data['end_time'] || (int)$activity['show_end_time'] < $data['end_time']){
            $this->error ='模板时间不在活动展示时间内！';
            return false;
        }
        //模板时间判断
        if($activity_theme_id > 0){
            $where['activity_theme_id'] = array('neq', $activity_theme_id);
        }
        $where['activity_id'] = $activity_id;
        $where['status'] = 1;
        $where['type'] = $data['type'];
        
        $result = D('ActivityThemeView')->where($where)->field('start_time,end_time')->select();//start_time,end_time
        //模块时间判断
        if($result){
            $index = 0;
            foreach ($result as $key=>$val){
                if($data['end_time'] <= (int)$val['start_time'] || $data['start_time'] >= (int)$val['end_time']){
                    continue;
                }else{
                    $index++;
                }
            }
            if($index > 0){
                $this->error ='模板展示时间冲突！';
                return false;
            }
        }
        return true;
    }
    
    /**
     * @todo    是否可以添加模板（判断展示时间）同活动同模板下
     * @param   $activity_id    活动ID
     *          $theme_id       模板ID
     *          $position       位置
     *          $data           数据(start_time,end_time)
     * @author  fang
     */
    public function isModuleAdd($activity_id, $theme_id ,$position, $activity_module_id ,$data){
        //模板时间判断
        $where_theme['activity_theme_id'] = $theme_id;
        $where_theme['status'] = 1;
        $theme = M('activity_theme')->field('start_time,end_time')->where($where_theme)->find();
        if((int)$theme['end_time'] < $data['start_time'] || (int)$theme['start_time'] > $data['end_time'] || (int)$theme['end_time'] < $data['end_time'] ){
            $this->error ='模块时间不在模板展示时间内！';
            return false;
        }
        //模块时间判断
        $table_pre = C('DB_PREFIX');
        $field = $table_pre.'activity_module.start_time,'.$table_pre.'activity_module.end_time';
        if($activity_module_id > 0){
            $where[$table_pre.'activity_theme_module.module_id'] = array('neq', $activity_module_id);
        }
        $where[$table_pre.'activity_theme_module.activity_id'] = $activity_id;
        $where[$table_pre.'activity_theme_module.theme_id'] = $theme_id;
        $where[$table_pre.'activity_theme_module.position'] = (int)$position;
        $where[$table_pre.'activity_module.status'] = 1;
        $table_pre = C('DB_PREFIX');
        $result = M('activity_theme_module')->join($table_pre.'activity_module on '.$table_pre.'activity_module.activity_module_id = '.$table_pre.'activity_theme_module.module_id')->field($field)->where($where)->select();
        //模块时间判断
        if($result){
            $index = 0;
            foreach ($result as $key=>$val){
                if($data['end_time'] <= (int)$val['start_time'] || $data['start_time'] >= (int)$val['end_time']){
                    continue;
                }else{
                    $index++;
                }
            }
            if($index > 0){
                $this->error ='模块展示时间冲突！';
                return false;
            }
        }
        return true;
    }
    
    /**
     * @todo    模板删除（删除模板下的模块）
     * @param   $id     模板的ID
     * @return  boolean
     */
    public function themeDelete($id){
        $where['activity_theme_id'] =   array('in',$id);
        $where_theme['theme_id'] = array('in', $id);
        $data['status'] = -1;
        //删除模板
        M()->startTrans();
        $theme_status = M('ActivityTheme')->where($where)->save($data);
        //获取模板的模块
        $module = M('ActivityThemeModule')->field('module_id')->where($where_theme)->select();
        $where_module['activity_module_id'] = array('in', array_column($module, 'module_id'));
        //删除模块
        $module_status = M('ActivityModule')->where($where_module)->save($data);
        if($module && $theme_status && $module_status){
            M()->commit();
            return true;
        }else{
            M()->rollback();
            return false;
        }
    }
    
    /**
     * @todo    获取模块位置列表
     * @author  fang
     */
    public function getModulePosition($where = array(),$order = 'module_id asc'){
        return M('ActivityThemeModule')->field('DISTINCT(position)')->where($where)->order($order)->select();
    }
    
    /**
     * @todo    获取某活动某模板下的模块组（预览功能调用）
     * @param   activity_id     活动ID
     *          theme_id        模板ID
     *          module_id       模板ID（有模板ID为预览功能，没有为展示页面）
     * @author  fang
     */
    public function getModuleList(){
        
        $type = (isMobile())? 1 : 0 ;
        $map = array();
        $activity_id = (int)I('id');
        $theme_id = (int)I('theme_id');
        $module_array = I('module_id');
        
        if($activity_id == 0 || $theme_id == 0){
            $this->error = "参数错误！";
            return false;
        }
        if(is_array($module_array)){
            $module_ids = array();
            $position_ids = array();
            foreach ($module_array[$theme_id] as $key=>$val){
                $module_ids[] = $val[0];
                $position_ids[] = $key;
            }
            if($module_ids && $position_ids){
                $map['module_id'] = array('in', $module_ids);
                $map['position'] = array('in', $position_ids);
            }
        }else{
            if((int)$module_array > 0){
                $map['module_id'] = (int)$module_array;
            }
             
        }
        //获取数据
        $result = $this->cacheData($activity_id, $theme_id, $map, $type);
        return $result;
    }
    
    /**
     * @todo    获取缓存操作
     */
    public function cacheChange($activity_id,$type,$data = 0){
        $cache_name = 'ACTIVITY_'.$activity_id.'_'.$type;
        switch ($data){
            case 0:
                return $cache_name;
                break;
            case 1:
                S($cache_name, null);
                break;
            case 2:
                if(is_array($activity_id)){
                    for ($i=0; $i<count($activity_id); $i++){
                        S('ACTIVITY_'.$activity_id[$i].'_0', null);
                        S('ACTIVITY_'.$activity_id[$i].'_1', null);
                    }
                }else{
                    S('ACTIVITY_'.$activity_id.'_0', null);
                    S('ACTIVITY_'.$activity_id.'_1', null);
                }
                break;
            default:
        }
    }
    
    
    /**
     * @todo    模板、模块缓存(预览)
     * @param   $activity_id    活动ID
     * @param   $theme_id       模板ID
     * @param   $type           来源判断（0网页，1手机）
     * @author  fang
     */
    public function cacheData($activity_id,$theme_id,$map,$type){
        //缓存字段
        /* $cache_name = $this->cacheChange($activity_id,$type);
        $data = S($cache_name);
        //已缓存
        if($data){
            return $data;
        } */
        //未缓存（模板/模块获取）
        $theme_field = 'content,content_head,content_foot,end_time';
        $theme_where['activity_theme_id'] = $theme_id;
        $theme_where['status'] = 1;
        //$theme_where['type'] = $type;
        $theme = M('activity_theme')->field($theme_field)->where($theme_where)->find();
        if($theme == null){
            $this->error = "模板不存在！";
            return false;
        }
        $table_pre = C('DB_PREFIX');
        $field = 'position,module_content,start_time,end_time';
        $join = $table_pre.'activity_module on '.$table_pre.'activity_module.activity_module_id = '.$table_pre.'activity_theme_module.module_id';
        $order = 'position asc';
        //预览无需时间条件
        if($map){
            $where = $map;
        }else{
            $where['start_time'] = array('elt', NOW_TIME);
            $where['end_time'] = array('gt', NOW_TIME);
        }
        $where['activity_id'] = $activity_id;
        $where['theme_id'] = $theme_id;
        $where['status'] = 1;
        $module = M('activity_theme_module')->field($field)->join($join)->order($order)->where($where)->select();
        if($module == null){
            $this->error = "模块不存在！";
            return false;
        }
        $module_position = $module_end_time = array();
        foreach ($module as $key=>$val){
            $module_position[$val['position']] = $val['module_content'];
            if((int)$val['end_time'] > 0){
                $module_end_time[] = $val['end_time'];
            }
        }
        //缓存有效时间
        if($module_end_time){
            $end_time = ((min($module_end_time) > $theme['end_time'])? $theme['end_time'] : min($module_end_time)) - NOW_TIME;
        }else{
            $end_time = 0;
        }
        //模块组合
        $out = $this->themeModuleRegular($theme['content']);
        if(false == $out){
            $this->error ='模板解析失败';
            return false;
        }
        $str = $theme['content'];
        foreach ($out[1] as $key=>$val){
            if(array_key_exists((int)$val,$module_position)){
                $str = str_replace($out[0][$key], $module_position[(int)$val], $str);
            }else{
                $str = str_replace($out[0][$key], '', $str);
            }
        }
        $str =  $theme['content_head'].PHP_EOL.$str.PHP_EOL.$theme['content_foot'];
        //数据缓存（预览不缓存）
        /* if(empty($map)){
            S($cache_name, $str, 7200);//$end_time
        } */
        return $str;
    }
    
    /**
     * @todo    根据活动ID获取当前的活动HTML（正式）
	 * @param  activity_id int 活动ID 必填
	 * @author fang
	 * @update 非天天特卖活动
     */
    public function getActivityContent($activity_id){
        //访问形式
        $type = (isMobile())? 1 : 0 ;
        //缓存字段
        $cache_name = $this->cacheChange($activity_id, $type);
        $data = S($cache_name);
        //已缓存
        if($data){
            return $data;
        }
        $table_pre = C('DB_PREFIX');
        //获取活动的模板类型（网页+手机）
        $theme_field = 'activity_theme_id,content,content_head,content_foot,end_time';
        $theme_join = $table_pre.'activity_theme_relation on '.$table_pre.'activity_theme_relation.theme_id = '.$table_pre.'activity_theme.activity_theme_id';
        $type_where['start_time'] = array('elt', NOW_TIME);
        $type_where['end_time'] = array('gt', NOW_TIME);
        $type_where['activity_id'] = $activity_id;
        $type_where['status'] = 1;
        $type_list = M('activity_theme')->field('type')->join($theme_join)->where($type_where)->select();
        if($type_list == null){
            $this->error = "活动或模板不存在！";
            return false;
        }
        //根据访问形式切换展示
        $type_array = array_unique(array_column($type_list, 'type'));
        //访问来源与模板不一致时:来源$type=1;模板$val=0
        if(!in_array($type, $type_array)){
            foreach ($type_array as $key=>$val){
                if($type != $val) $type = $val;
            }
        }
        //获取模板
        $theme_where['start_time'] = array('elt', NOW_TIME);
        $theme_where['end_time'] = array('gt', NOW_TIME);
        $theme_where['activity_id'] = $activity_id;
        $theme_where['status'] = 1;
        $theme_where['type'] = $type;
        $theme = M('activity_theme')->field($theme_field)->join($theme_join)->where($theme_where)->find();
        /* if($theme == null){
            $this->error = "活动或模板不存在！";
            return false;
        } */
        //获取模块
        $field = 'position,module_content,start_time,end_time';
        $join = $table_pre.'activity_module on '.$table_pre.'activity_module.activity_module_id = '.$table_pre.'activity_theme_module.module_id';
        $order = 'position asc';
        $where['start_time'] = array('elt', NOW_TIME);
        $where['end_time'] = array('gt', NOW_TIME);
        $where['activity_id'] = $activity_id;
        $where['theme_id'] = $theme['activity_theme_id'];
        $where['status'] = 1;
        $module = M('activity_theme_module')->field($field)->join($join)->order($order)->where($where)->select();

        if($module == null){
            $this->error = "模块不存在！";
            return false;
        }
        $module_position = $module_end_time = array();
        foreach ($module as $key=>$val){
            $module_position[$val['position']] = $val['module_content'];
            if((int)$val['end_time'] > 0){
                $module_end_time[] = $val['end_time'];
            }
        }
        //缓存有效时间
        if($module_end_time){
            $end_time = ((min($module_end_time) > $theme['end_time'])? $theme['end_time'] : min($module_end_time)) - NOW_TIME;
        }else{
            $end_time = 0;
        }
        //模块组合
        $out = $this->themeModuleRegular($theme['content']);
        if(false == $out){
            $this->error ='模板解析失败';
            return false;
        }
        $str = $theme['content'];
        foreach ($out[1] as $key=>$val){
            if(array_key_exists((int)$val,$module_position)){
                $str = str_replace($out[0][$key], $module_position[(int)$val], $str);
            }else{
                $str = str_replace($out[0][$key], '', $str);
            }
        }
        $str =  $theme['content_head'].PHP_EOL.$str.PHP_EOL.$theme['content_foot'];
        //活动页面缓存
        //S(array('prefix' => 'tke_admin_'));
        S($cache_name, $str, 3600);//$end_time
        //S(array('prefix' => C('DATA_CACHE_PREFIX')));
        return $str;
    }
    
    /**
     * @todo    获取活动名称
     * @author  fang
     */
    public function getActivityName($where = array('status' => 1)){
        return M('activity')->where($where)->getField('activity_name');
    }
    
    /**
     * @todo    获取主题名称
     * @author  fang
     */
    public function getThemeName($where = array('status' => 1)){
        return M('activity_theme')->where($where)->getField('theme_name');
    }
    
    /**
     * @todo    获取模板有效时间
     * @author  fang
     */
    public function getThemeTime($where = array('status' => 1)){
        return M('activity_theme')->field('start_time,end_time')->where($where)->find();
    }
    
    
    /**
     * @todo    获取模板信息
     * @author  fang
     */
    public function getTheme($where = array('status' => 1), $field = true){
        return D('ActivityThemeView')->where($where)->field($field)->find();
    }
    
    /**
     * @todo    获取模块信息
     * @author  fang
     */
    public function getModule($where = array('status' => 1), $field = true){
        return D('ActivityModuleView')->where($where)->field($field)->find();
    }
   
    /**
     * @todo    获取模板列表
     * @author  fang
     */
    public function getThemeList($map=array('status'=>1),$order='sort desc',$field='activity_theme_id,theme_name'){
    	return M('ActivityTheme')->field($field)->where($map)->order($order)->select();
    }
    
    /**
     * @todo 活动分类
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
	public function getActivityCategory($map=array('status'=>1),$order='sort desc',$field="category_name,activity_category_id"){
		return M('ActivityCategory')->field($field)->where($map)->order($order)->select();
	}

	
	/**
	 * @todo 获取活动list
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function getActivityList($map=array('status'=>1,'parent_id'=>0),$order='sort desc',$field="activity_id,activity_name"){
		return $this->field($field)->where($map)->order($order)->select();
	}
	
	/**
	 * @todo 获取活动详细信息
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function getActivityDetail($map=array('status'=>1),$field=true){
		return D('ActivityDetailView')->field($field)->where($map)->find();
	}
	
	/**
	 * @todo 返回活动回顾图片list
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function getActivityPictureList($map,$field='path'){
		return D('ActivityPictureView')->field($field)->where($map)->select();
	}
	
	/**
	 * @todo 修改活动详细信息
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function updateActivityDetail(){
		$data = I('request.'); 
		$id = (int)$data[$this->getPk()];
		if($id ==0){
			$this->error = '请不要非法攻击.~！';
			return false;
		}
		$map = array($this->getPk()=>$id);
		if(false === $this->activityDetailIs($map)){
			$this->error = '请不要非法攻击.~！';
			return false;
		}
		unset($data[$this->getPk()]);
		$status = M('ActivityDetail')->where($map)->save($data); //更新基础内容
		if(false === $status){
			$this->rollback();
			$this->error = '更新出错！';
			return false;
		}
		//记录行为
		action_log('activity_edit', 'activity', $id, UID);
		return true;
	}
	
	/**
	 * @todo 上传活动回顾图片
	 * @param int pic_id 图片id
	 * @param int activity_id 活动id
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function uploadActivityPicture(){
		$pic_id = (int)I('pic_id');
		$activity_id = (int)I('activity_id');
		if($pic_id==0 || $activity_id ==0){
			$this->error = '参数有误 ！';
			return false;
		}
		if(!$this->activityIs(array('activity_id'=>$activity_id,'status'=>1))){
			$this->error= '当前活动不存在或已经被禁用删除';
			return false;
		}
		if(M('ActivityPicture')->add(array('pic_id'=>$pic_id,'activity_id'=>$activity_id),array(),true)){
		    //记录行为
		    action_log('activity_pic_add', 'activity_picture', $pic_id, UID);
			return true;
		}else{
			$this->error = '活动附件表写入失败！';
			return false;
		}
		
	}
	
	/**
	 * @todo 删除活动回顾图片
	 * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
	 */
	public function delActivityPic(){
		$pic_id = (int)I('pic_id');
		$activity_id = (int)I('activity_id');
		if($pic_id==0 || $activity_id ==0){
			$this->error = '参数有误 ！';
			return false;
		}
		if(M('ActivityPicture')->where(array('activity_id'=>$activity_id,'pic_id'=>$pic_id))->delete()){
		    //记录行为
		    action_log('activity_pic_delete', 'activity_picture', $pic_id, UID);
			return true;
		}else{
			$this->error = '活动回顾图片删除失败！'.M()->_sql();
			return false;
		}
	}
	
	/**
	 * @todo   正则筛选规则标签<jjhh></jjhh>
	 * @author fang
	 * @return array
	 */
	static private  function themeModuleRegular($content){
	    preg_match_all('/\<jjhh\>(.*?)\<\/jjhh\>/s', $content, $out);
	    if(!$out[1]){
	        return false;
	    }
	    return $out;
	}
	
	/**
	 * @todo 记录活动操作log
	 * @param int|array activity_id  活动id.
	 * @param int uid 	操作人id
	 * @param int log_type 操作状态 1-创建,2-修改,3-通过,4-未通过,5-上线,6-下线,7-删除,8-禁用,9-启用
	 * @return boolean true 成功 false 失败
	 * @author PHP@妖孽<mashengjie@hrbjjhh.com>
	 */
	public function activityLogInsert($activity_id,$log_type,$uid=UID){
		if(!is_array($activity_id)){
			$activity_id = (int)$activity_id;
		}else{
			$this->error='暂不支持数组,后期拓展';
			return false;
		}
	
		if($activity_id ==0){
			$this->error='活动参数非法';
			return false;
		}
		$log_array = array(1,2,3,4,5,6,7,8,9);//活动状态允许插入的 集合.
		$log_type = (int)$log_type;
		if($log_type==0 || !in_array($log_type,$log_array)){
			$this->error='操作状态改参数非法';
			return false;
		}
		if(!$this->activityIs(array('status'=>1,'activity_id'=>$activity_id))){
			$this->error='活动不存在或已被删除禁用';
			return false;
		}
		$data = array();//构建要插入的数据
		$data['activity_id']=$activity_id;
		$data['uid']=$uid;
		$data['log_type']=$log_type;
		$data['create_time']=NOW_TIME;//操作时间
		if(!M('ActivityLog')->add($data)){
			$this->error='log表插入失败';
			return false;
		}
		return true;
	}
	
	
	/**
	 * @todo 获取活动loglist
	 * @param int activity_id  活动id.
	 * @return array()
	 * @author PHP@妖孽<mashengjie@hrbjjhh.com>
	 */
	public function getActivityLog($activity_id){
		if(!is_array($activity_id)){
			$activity_id = (int)$activity_id;
		}else{
			$this->error='暂不支持数组,后期拓展';
			return false;
		}
		return D('ActivityLogView')->where(array('activity_id'=>$activity_id))->order('log_id asc')->select();
	}
	
	
	/**
	 * @todo 创建活动智能表单
	 * @param int activity_id  活动id.
	 * @return array()
	 * @author PHP@妖孽<mashengjie@hrbjjhh.com>
	 */
	public function createForm(){
		$activity_id = (int)I('activity_id');
		if($activity_id ==0){
			$this->error='请不要非法访问~';
			return false;
		}
		//判断活动是否存在,
		if(!$this->activityIs(array('status'=>1,'activity_id'=>$activity_id))){
			$this->error='当前活动已被禁用或删除.~';
			return false;
		}
		$table_name =  C('DB_PREFIX').'activity_attached_'.$activity_id;//附属标名称
		$config_obj = D('ActivityConfig');
		$info = $config_obj->checkTableExist($activity_id);
		if(!empty($info)){
			//存在的话是否有数据
			$count =M()->query("select count(*) as num from {$table_name};");
			//如果有数据就驳回,
			if(array_key_exists('num', $count['0']) && $count['0']['num']>0){
				$this->error  = '当前活动已产生报名数据,~不能再更新表单';
				return  false;
			}
		}
		//继续创建数据表
		//获取活动的配置情况,
		$config_list = $config_obj->getActivityConfig($activity_id);
		if(empty($config_list)){
			$this->error = '请生成表单字段.~再来操作';
			return false;
		}
		$attribute_obj = D('Attribute','Service');
		$attribute_obj->table_name = $table_name;
		//执行创建
		//如果没有数据可以重新创建.
		$is_true = $attribute_obj->addField($config_list);
		if(true===$is_true){
			return true;
		}else{
			$this->error =$attribute_obj->getError();
			return  false;
		}
	}

	
	/**
	 * @todo 活动报名(对外api)
	 * @param activity_id int 活动id
	 * @param user_name string(20) 用户姓名
	 * @param mobile_phone string(11)手机号
	 * @param type int 0,1 0默认已报名返回用户Id, 1,已报名返回提示信息
	 * @author PHP@妖孽 <dino_ma@163.com>
	 */
	public function joinActivity($api_data,$type){
		if(empty($api_data)){
			$data = I('request.');
		}else{
			$data = $api_data;
		}

		if(empty($data)){
			$this->error ='报名数据不能为空.~';
			return false;
		}
		
		//姓名和手机号是必须有的
	/* 	$data['activity_id']=1;
		$data['user_name'] = 'test';
		$data['mobile_phone'] = '132635121'.rand('00', '99'); */
		if(!array_key_exists('activity_id', $data)){
			$this->error ='活动id必须存在.~';
			return false;
		}
// 		if(!array_key_exists('user_name', $data)){
// 			$this->error ='用户名必须存在.~';
// 			return false;
// 		}
		if(!array_key_exists('mobile_phone', $data)){
			$this->error ='手机号必须存在.~';
			return false;
		}
		if (!preg_match("/^1[3-8][0-9]{9}$/",$data['mobile_phone'])){
			$data['mobile_phone'] = (int)$data['mobile_phone'];
			if($data['mobile_phone']==0){
				$this->error ='customer_id 有问题~';
				return false;
			}
		}
		
		$activity_id = (int)$data['activity_id'];
		if($activity_id ==0){
			$this->error ='参数有误';
			return false;
		}
// 		$activity_info = $this->activityIs(array('status'=>1,'activity_id'=>$activity_id));
// 		if(!$activity_info){
// 			$this->error ='活动不存在或已被删除禁用~.~';
// 			return false;
// 		}
		if(strlen($data['customer_name'])>15){
			$this->error ='用户名不能大于10个字';
			return false;
		}
		//验证数据和配置信息是否相符,.提出相符的进行写入,
// 		$config_info = D('Admin/ActivityConfig')->getActivityConfig($activity_id);
		$join_obj =D('Admin/ActivityJoin');
	/* 	$fields =null;
		for ($i=0;$i<count($join_obj->fields);$i++){
			if(isset($join_obj->fields[$i])){
			    if(!is_null($join_obj->fields[$i])){
			        $fields[]=$join_obj->fields[$i];
			    }
			}
		}
		$fields = array_merge(array('mobile_phone','customer_name'),$fields);
		if(!empty($config_info)){
			$config_list = array_column($config_info, 'name');//获取所有字段
			foreach($data as $key=>$val){
				if(!in_array($key,$fields)){
					if( !in_array($key, $config_list)){
						unset($data[$key]);
					}
				}
			}
		}else{
			foreach($data as $key=>$val){
                if(!in_array($key,$fields)){
					unset($data[$key]);
				}
			}
		} */
// 		$_POST = $data;
		if(!array_key_exists('ticket_level', $data) || is_null($data['ticket_level'])){
			$data['ticket_level']=0;//默认普通票
		}
		if($customer_id = $join_obj->update($data,$type)){
			return $customer_id;
		}else{
			$this->error =$join_obj->getError();
			return false;
		}
	}
	
    /**
     * @todo 活动签到
     * @param activity_id 活动id
     * @param customer_id 用户id
     */
// 	public function activitySign($activity_id,$customer_id){
// 	    $customer_id = (int)$customer_id;
// 	    $activity_id = (int)$activity_id;
// 	    if($activity_id ==0){
// 	        $this->error = '活动参数有问题.~';
// 	        return false;
// 	    }
// 	    if($customer_id ==0){
// 	        $this->error = '用户id参数有问题.~';
// 	        return false;
// 	    }
// 	    $obj = M('ActivityJoin');
// 	    if(false !== $obj->where(array('activity_id'=>$activity_id,'customer_id'=>$customer_id))->save(array('is_signin'=>1,'signin_time'=>NOW_TIME))){
// 	        return true;
// 	    }else{
// 	        $this->error = $obj->getError();
// 	        return false;
// 	    }
// 	}
	
}
